package com.yhsoft.interceptor;

import com.yhsoft.common.exception.ErrorMsg;
import com.yhsoft.common.vo.Result;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.apache.tomcat.util.http.fileupload.impl.SizeLimitExceededException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;

import java.util.List;


/**
 * 自定义全局异常处理器
 */
@ControllerAdvice
public class ExceptionHandlerContrller {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandlerContrller.class);

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result<List<ErrorMsg>> exception(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        StringBuilder stringBuilder = new StringBuilder();
        if (result.hasErrors()) {
            List<ObjectError> errors = result.getAllErrors();
            errors.forEach(p -> {
                FieldError fieldError = (FieldError) p;
                logger.warn("Bad Request Parameters: dto entity [{}],field [{}],message [{}]", fieldError.getObjectName(), fieldError.getField(), fieldError.getDefaultMessage());
                stringBuilder.append(fieldError.getDefaultMessage());
            });
        }
        return Result.fail(stringBuilder.toString());
    }

    /**
     * 文件上传超过最大限制异常
     *
     * @return R
     */
    @ExceptionHandler(value = MultipartException.class)
    public @ResponseBody
    Result handleBusinessException(MaxUploadSizeExceededException ex) {
        String msg;
        if (ex.getCause().getCause() instanceof FileSizeLimitExceededException) {
            logger.error(ex.getMessage());
            msg = "[单文件大小不得超过5M]";
        } else if (ex.getCause().getCause() instanceof SizeLimitExceededException) {
            logger.error(ex.getMessage());
            msg = "[总上传文件大小不得超过10M]";
        } else {
            msg = "请检查文件类型及大小是否符合规范";
        }

        return Result.fail(500,msg);

    }
}
